package com.zhengsr.corelib.net.intecepter;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.zhengsr.CoreManager;
import com.zhengsr.corelib.utils.Contracts;
import com.zhengsr.corelib.utils.Lgger;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class AddCookiesInterceptor implements Interceptor {

    private static final String COOKIE_PREF = "cookies_prefs";
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        String cookie = getCookie(request.url().host());
        if (!TextUtils.isEmpty(cookie)) {
            builder.addHeader("Cookie", cookie);
            //Log.i(LogTAG.cookie, "interceptor addHeader Cookie: "+cookie);
            Lgger.d("zsr --> interceptor add hec: "+cookie);
        }
        return chain.proceed(builder.build());
    }

    private String getCookie(String host) {

        SharedPreferences sp = CoreManager.getContext().getSharedPreferences(Contracts.COOKIE_SPREF,
                Context.MODE_PRIVATE);

        String cookie = sp.getString(host, "");
        return cookie;
    }

}